package com.zyl.familyspaceauth.shiro.filter;
/*
 * Project: com.sunyard.am.shiro.filter
 *
 * File Created at 2021/7/2
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only in accordance with the terms of the license.
 */

import com.zyl.familyspacecommoncore.result.Result;
import com.zyl.familyspacecommoncore.result.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zyl
 * @Desc 继承自FormAuthenticationFilter，
 * 用于实现一个认证过滤器。其主要功能是在处理请求之前检查用户是否已经通过认证
 *
 * @date 2021/7/2 13:34
 */
public class AuthFilter extends FormAuthenticationFilter {
    /**
     * onPreHandle方法在处理请求之前被调用，它接收请求和响应对象以及映射值作为参数。
     * 在这个方法中，它通过SecurityUtils.getSubject().isAuthenticated()方法检查当前用户是否已经通过认证
     * @param servletRequest
     * @param servletResponse
     * @param mappedValue
     * @return
     * @throws Exception
     */
    @Override
    public boolean onPreHandle(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue)
            throws Exception {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            printToPage(servletResponse, Result.error("登录状态已失效，请重新登录", ResultCode.NO_LOGIN_AUTH));
            return false;
        }
        return true;
    }

    /**
     * 返回result
     * @param servletResponse 响应头
     * @param result result
     * @throws IOException io异常
     */
    private void printToPage(ServletResponse servletResponse, Result result) throws IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(com.sunyard.framework.common.util.conversion.JsonUtils.toJSONString(result));
        writer.flush();
        writer.close();
    }
}